<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<% String path = request.getContextPath(); %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	
	<h1>你好</h1>
	
<script type="text/javascript">
var websocket = null;
if("WebSocket" in window){
	initSocket();
}else{
	alert('当前浏览器 Not support websocket');
}
console.log(window.location.host);

function initSocket(){
	webSocket = new WebSocket(window.location.host+"<%=path%>/websoket");
	
	//连接发生错误的回调方法
    webSocket.onerror = function () {
        setMessageInnerHTML("WebSocket连接发生错误");
    };
 
    //连接成功建立的回调方法
    webSocket.onopen = function () {
//        setMessageInnerHTML("WebSocket连接成功");
        webSocket.send("测试消息");
    }
 
    //接收到消息的回调方法
    webSocket.onmessage = function (event) {
        setMessageInnerHTML(event.data);
    }
 
    //连接关闭的回调方法
    webSocket.onclose = function () {
        setMessageInnerHTML("WebSocket连接关闭");
    }
 
 
    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
 
    window.onbeforeunload = function () {
 
        closeWebSocket();
 
    }
 
    //将消息显示在网页上
 
    function setMessageInnerHTML(innerHTML) {
 
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
 
    }
 
    function closeWebSocket() {
 
    	webSocket.close();
 
    }
 
 
    function clear(){
        document.getElementById('message').innerHTML="";
    }
 
    //发送消息
 
    function send() {
 
        var message = document.getElementById('text').value;
 
        webSocket.send(message);
 
    }
   
}

</script>
</body>
</html>